import { onMounted, ref } from "vue";
interface ScriptOptions {
  src: string | string[];
}
export function useScript() {
  const isLoading = ref(false);
  const error = ref(false);
  const success = ref(false);

  const initScript = (src: string) => {
    return new Promise((resolve, reject) => {
      onMounted(() => {
        const script = document.createElement("script");
        script.type = "text/javascript";
        script.onload = function () {
          isLoading.value = false;
          success.value = true;
          error.value = false;
          resolve("");
        };
        script.onerror = function (err) {
          isLoading.value = false;
          success.value = false;
          error.value = true;
          reject(err);
        };

        script.src = src;
        document.head.appendChild(script);
      });
    });
  };
  const loadScript = (opts: ScriptOptions) => {
    let { src } = opts;
    if (typeof src === "string") {
      src = src.split(",") as string[];
    }
    const arr: Promise<unknown>[] = [];
    src.forEach((str) => {
      arr.push(initScript(str));
    });
    return Promise.all(arr);
  };

  return {
    isLoading,
    error,
    success,
    loadScript,
  };
}
